// pages/productDetails/index.js
const app = getApp();

import {
  getPackageList,
  order
} from "../../api/productDetails";
import Message from "tdesign-miniprogram/message/index"; //消息通知

Page({

  /**
   * 页面的初始数据
   */
  data: {
    product: '',
    imageUrl: app.globalData.imgUrl + "miniprogram/images/package_59.jpg"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    getPackageList()
      .then((res) => {
        const product = res.data.find(item => item.id == options.id) || {};
        this.setData({
          product,
        });
      })
      .catch(() => {
        Toast("商品加载失败，请稍后重试");
      });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  onHandleNow() {
    // 立即办理按钮点击事件
    wx.showToast({
      title: '立即办理',
      icon: 'success'
    });
    // 这里可以跳转到办理页面或发起下单
    if (!app.globalData.mobile) {
      wx.showToast({
        title: "未绑定手机!",
        icon: "error",
      });
      return;
    }
    // 办理套餐信息
    console.log(this.data.product);
    // 下单并发送请求至后端，并用变量接收返回的res.data
    order(this.data.product.id)
      .then((res) => {
        const orderId = res.data; // 这里接收后端返回的data
        console.log("当前订单：" + orderId);
        this.showSuccessMessage(orderId);
        //跳转支付
        wx.navigateTo({
          url: "/pages/orderDetails/index?orderId=" + orderId + "&state=0",
        })
      })
      .catch(() => {
        this.showErrorMessage();
      });
  },
  //下单成功消息通知
  showSuccessMessage() {
    Message.success({
      context: this,
      visible: true, //隐藏时销毁组件
      duration: 5000,
      content: "下单成功,跳转支付",
    });
  },
  //下单失败消息通知
  showErrorMessage() {
    Message.error({
      context: this,
      visible: true, //隐藏时销毁组件
      duration: 5000,
      content: "下单失败,",
    });
  },
})